using UnityEngine;

//泛型单例
public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    private static T instance;

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType<T>();
                if (instance == null)
                {
                    GameObject obj = new GameObject(typeof(T).Name);
                    instance = obj.AddComponent<T>();
                }
            }
            return instance;
        }
    }

    public virtual void Awake() {
        if(instance == null){
            instance = this as T;
            //确保单例对象在场景切换时不会被销毁
            DontDestroyOnLoad(gameObject);
        }else{
            Destroy(gameObject);
        }
    }
}


